import frpOption from "../option.json" with { type: "json" }
import { frpFetch, getOrderId, throwFerchError } from "./util.js"
import logger from "./logger.js"

async function fullOrderToProject(orderCode, orderId) {
    if (!orderId) {
        orderId = await getOrderId(orderCode)
    }

    const retryTime = 3
    let currRetry = 0
    let isSuccess = false
    const errMsg = []
    while (!isSuccess && currRetry < retryTime) {
        const changeOldOrderStepRes = await fetch(`${frpOption.api.changeOldOrderStep}`, {
            method: "post",
            body: JSON.stringify({ orderCode: orderCode }),
        }).then((res) => res.json())
        if (changeOldOrderStepRes.code === 200) {
            isSuccess = true
            break
        }
        currRetry += 1
        errMsg.push(changeOldOrderStepRes)

        const randomWait = Math.floor(Math.random() * 5000) + 2000
        await new Promise(res => setTimeout(res, randomWait))
    }
    if (!isSuccess) {
        throwFerchError(errMsg, "完整订单提交失败")
    }

    logger.info(`${orderCode} 完整订单提交成功`)

    await changeOrderStep(orderCode, orderId)
}

async function changeOrderStep(orderCode, orderId) {
    // if (!orderId) {
    //     orderId = await getOrderId(orderCode)
    // }

    // const getProductionRes = await frpFetch(frpOption.api.getFormList, {
    //     offset: 0,
    //     limit: 1,
    //     formCode: "productionOrder",
    //     filter: `orderId = ${orderId} AND deliverType != 5 AND afterSaleType NOT IN (-2, -3)`,
    //     action: "编辑",
    //     auth: 52,
    // })
    // if (getProductionRes.code !== 200) {
    //     throwFerchError(getProductionRes, "获取生产订单失败")
    // }

    // if (getProductionRes.data.length !== 0) {
    //     const predictToKingdeeRes = await fetch(`${frpOption.api.predictToKingdee}`, {
    //         method: "post",
    //         body: JSON.stringify({ orderId: orderId }),
    //     }).then((res) => res.json())
    //     if (predictToKingdeeRes.code !== 200) {
    //         throwFerchError(predictToKingdeeRes, "predictToKingdee失败")
    //     }
    // }
    // logger.info(`${orderCode}predictToKingdee成功`)

    const changeOrderStepRes = await frpFetch(frpOption.api.changeOrderStep, {
        orderCode: orderCode,
    })
    if (changeOrderStepRes.code !== "success") {
        throwFerchError(changeOrderStepRes, "changeOrderStep")
    }
    logger.info(`${orderCode} changeOrderStep成功`)
}

export { fullOrderToProject, changeOrderStep }